<?php
namespace App\Models\V1;
use DB;


class MessageModel{

    /*获得总的信息*/
    public function get_user_message($userId){
        $messages = DB::table('note_user_message as a')
            ->leftJoin('note_message_list as b','b.msg_id','=','a.msg_id')
            ->where('a.user_id',$userId)
            ->select('a.id as userMsgId','b.msg_id','b.msg_title','b.msg_content','b.add_time','a.is_readed')
            ->orderBy('b.add_time','DESC')
            ->get();
        return $messages;
    }


    /**
     * 阅读用户信息
     * */
    public function read_user_message($userId){
        DB::table('note_user_message')->where('user_id',$userId)->update(['is_readed'=>1]);
        return true;
    }


    /*获得未读的消息数量*/
    public function get_unreaded_message_number($userId){
        $msgNumber = DB::table('note_user_message')
            ->where('user_id',$userId)
            ->where('is_readed',0)
            ->count();
        return $msgNumber;
    }


    /**
     * 添加日记消息
     * */
    public function add_note_message($title,$content){
        $data = [
            'msg_title'     => $title,
            'msg_content'   => $content,
            'add_time'      => date_time()
        ];
        $id = DB::table('note_message_list')->insertGetId($data);
        return $id;
    }


    /**
     * 添加用户提示信息
     * */
    public function add_user_message($msgId,$userId){
        if(is_array($userId)){
            $data = [];
            foreach($userId as $id){
                $singleData = ['user_id'=>$id,'msg_id'=>$msgId,'is_readed'=>0];
                array_push($data,$singleData);
            }
        }else{
            $data = ['user_id'=>$userId,'msg_id'=>$msgId,'is_readed'=>0];
        }
        return DB::table('note_user_message')->insert($data);
    }
}